//
//  AppDelegate.m
//  AppointmentForCar
//
//  Created by Herron on 16/9/26.
//  Copyright © 2016年 Herron. All rights reserved.
//

#import "AppDelegate.h"
#import <MMDrawerController.h>
#import "UIViewController+MMDrawerController.h"
#import "HomeViewController.h"
#import "MyCenterViewController.h"
#import "MMDrawerController.h"
#import "LoginViewController.h"
#import "PushManager.h"
#import "MapManager.h"

#define kWeChatAPPID @"wx798b72b52619ba36"
@interface AppDelegate ()<BMKGeneralDelegate, WXApiDelegate, UIAlertViewDelegate>

@end

@implementation AppDelegate

#pragma mark - life cycle
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // 微信支付
    [WXApi registerApp:kWeChatAPPID withDescription:@"demo 2.0"];
    // 个推
    [PushManager sharePushManager].pushSwith = NO;
    // 百度地图
    [MapManager shareMapManager];
    self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
    self.window.backgroundColor = [UIColor whiteColor];
    [self setRootViewController];
    [self setNavigationBarAppearances];
    if([UserAccountManager shareUserManager].loginStatus)
    {
        [self noticeServicerPushClientId];
    }
    return YES;
}

- (void)applicationWillResignActive:(UIApplication *)application {
}

- (void)applicationDidEnterBackground:(UIApplication *)application {
}

- (void)applicationWillEnterForeground:(UIApplication *)application {
}

- (void)applicationDidBecomeActive:(UIApplication *)application {
}

- (void)applicationWillTerminate:(UIApplication *)application {
}



#pragma mark - Private Method
- (void)setRootViewController {
   if([UserAccountManager shareUserManager].loginStatus)
   {
       [self.window setRootViewController:[self homeController]];
   } else
   {
       [self.window setRootViewController:[self loginController]];
   }
    [self.window makeKeyAndVisible];
}

- (UIViewController *)loginController
{
    LoginViewController * controller = [[LoginViewController alloc] init];
    return controller;
}

- (UIViewController *)homeController
{
    UIViewController * myCenterVC = [[MyCenterViewController alloc] init];
    UINavigationController *leftNav = [[UINavigationController alloc] initWithRootViewController:myCenterVC];
    HomeViewController *controller = [[HomeViewController alloc] init];
    UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:controller];
    
    MMDrawerController * drawerController = [[MMDrawerController alloc]
                                             initWithCenterViewController:nav
                                             leftDrawerViewController:leftNav
                                             rightDrawerViewController:nil];
    [drawerController setShowsShadow:YES];
    [drawerController setMaximumLeftDrawerWidth:200];
    [drawerController setOpenDrawerGestureModeMask:MMOpenDrawerGestureModeAll];
    [drawerController setCloseDrawerGestureModeMask:MMCloseDrawerGestureModeAll];
    [drawerController showsShadow];
    return drawerController;
}

- (void)setNavigationBarAppearances {
    [[UINavigationBar appearance] setBarTintColor:[UIColor whiteColor]];
    [[UINavigationBar appearance] setTitleTextAttributes:@{NSFontAttributeName:[UIFont systemFontOfSize:18], NSForegroundColorAttributeName:[UIColor blackColor]}];
    [[UINavigationBar appearance] setTranslucent:NO];
    [[UINavigationBar appearance] setTintColor:kColorFontGray];
    [[UIBarButtonItem appearance] setBackButtonTitlePositionAdjustment:UIOffsetMake(0, -60) forBarMetrics:UIBarMetricsDefault];
}

- (void)onGetNetworkState:(int)iError
{
    if (0 == iError) {
        NSLog(@"联网成功");
    }
    else{
        NSLog(@"onGetNetworkState %d",iError);
    }
}

- (void)onGetPermissionState:(int)iError
{
    if (0 == iError) {
        NSLog(@"授权成功");
    }
    else {
        NSLog(@"onGetPermissionState %d",iError);
    }
}


/**
 *  推送相关
 */
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult result))completionHandler
{
    [[PushManager sharePushManager] getPushInfo:userInfo];
    completionHandler(UIBackgroundFetchResultNewData);
}
- (void)application:(UIApplication *)application performFetchWithCompletionHandler:(void (^)(UIBackgroundFetchResult result))completionHandler
{
    [GeTuiSdk resume];
    completionHandler(UIBackgroundFetchResultNewData);
}


/** 远程通知注册成功委托 */
- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
    NSString *token = [[deviceToken description] stringByTrimmingCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@"<>"]];
    token = [token stringByReplacingOccurrencesOfString:@" " withString:@""];
    NSLog(@"\n>>>[DeviceToken Success]:%@\n\n", token);
    
    //向个推服务器注册deviceToken
    [PushManager sharePushManager].cid = token;
    [GeTuiSdk registerDeviceToken:token];
}


#pragma mark - netWork
// 通知服务器记录客户端的推送号
- (void)noticeServicerPushClientId
{
    [[PushManager sharePushManager] getClientID:^(NSString *cid) {
        [NetWork postNetWorkWithUrl:@"push-notice-clientId" parame:@{@"clientId":cid,@"osType":@"ios",@"id":[UserAccountManager shareUserManager].user.driverId,@"type":@"2"} successBlock:^(NSDictionary *dic) {
        } errorBlock:^(id error) {
        }];
    }];
}

#pragma mark - 支付宝
//支付成功时调用，回到第三方应用中
- (BOOL)application:(UIApplication *)application
            openURL:(NSURL *)url
  sourceApplication:(NSString *)sourceApplication {
    // 微信
    if ([url.scheme isEqualToString:kWeChatAPPID]) {
        return  [WXApi handleOpenURL:url delegate:(id<WXApiDelegate>)self];
    } else {
        // 支付宝
        if ([url.host isEqualToString:@"safepay"]) {
            // 支付跳转支付宝钱包进行支付，处理支付结果
            [[AlipaySDK defaultService] processOrderWithPaymentResult:url standbyCallback:^(NSDictionary *resultDic) {
                NSLog(@"result = %@",resultDic);
            }];
            
            // 授权跳转支付宝钱包进行支付，处理支付结果
            [[AlipaySDK defaultService] processAuth_V2Result:url standbyCallback:^(NSDictionary *resultDic) {
                NSLog(@"result = %@",resultDic);
                // 解析 auth code
                NSString *result = resultDic[@"result"];
                NSString *authCode = nil;
                if (result.length>0) {
                    NSArray *resultArr = [result componentsSeparatedByString:@"&"];
                    for (NSString *subResult in resultArr) {
                        if (subResult.length > 10 && [subResult hasPrefix:@"auth_code="]) {
                            authCode = [subResult substringFromIndex:10];
                            break;
                        }
                    }
                }
                NSLog(@"授权结果 authCode = %@", authCode?:@"");
            }];
        }
        return YES;
    }
}

#pragma mark - NOTE: 9.0以后使用新API接口
- (BOOL)application:(UIApplication *)app openURL:(NSURL *)url options:(NSDictionary<NSString*, id> *)options {
    
    if ([url.scheme isEqualToString:kWeChatAPPID]) {
        /*! @brief 处理微信通过URL启动App时传递的数据
         *
         * 需要在 application:openURL:sourceApplication:annotation:或者application:handleOpenURL中调用。
         * @param url 微信启动第三方应用时传递过来的URL
         * @param delegate  WXApiDelegate对象，用来接收微信触发的消息。
         * @return 成功返回YES，失败返回NO。
         */
        
        return [WXApi handleOpenURL:url delegate:self];
    } else {
        
        if ([url.host isEqualToString:@"safepay"]) {
            // 支付跳转支付宝钱包进行支付，处理支付结果
            [[AlipaySDK defaultService] processOrderWithPaymentResult:url standbyCallback:^(NSDictionary *resultDic) {
                NSLog(@"支付宝支付result = %@",resultDic);
                UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"支付结果" message:@"成功！" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
                [alert show];

                AppDelegate *appDelegate = kAppDelegate;
                [appDelegate setRootViewController];
            }];
            
            // 授权跳转支付宝钱包进行支付，处理支付结果
            [[AlipaySDK defaultService] processAuth_V2Result:url standbyCallback:^(NSDictionary *resultDic) {
                NSLog(@"支付宝result = %@",resultDic);
                // 解析 auth code
                NSString *result = resultDic[@"result"];
                NSString *authCode = nil;
                if (result.length>0) {
                    NSArray *resultArr = [result componentsSeparatedByString:@"&"];
                    for (NSString *subResult in resultArr) {
                        if (subResult.length > 10 && [subResult hasPrefix:@"auth_code="]) {
                            authCode = [subResult substringFromIndex:10];
                            break;
                        }
                    }
                }
                NSLog(@"授权结果 authCode = %@", authCode?:@"");
            }];
        }
        return YES;
    }
}

#pragma mark - 微信支付回调
- (void)onResp:(BaseResp*)resp
{
    NSString *strMsg = [NSString stringWithFormat:@"errcode:%d", resp.errCode];
    NSString *strTitle = @"支付结果";
    
    if([resp isKindOfClass:[PayResp class]]){
        
        switch (resp.errCode) {
            case WXSuccess:
            {
                strMsg = @"支付结果：成功！";
                break;
            }
            case WXErrCodeUserCancel:
                strMsg = @"支付结果：用户点击取消！";
                break;
            case WXErrCodeSentFail:
                strMsg = @"支付结果：发送失败！";
                break;
            case WXErrCodeAuthDeny:
                strMsg = @"支付结果：授权失败！";
                break;
            default:
                strMsg = @"支付结果：微信不支持！";
                break;
        }
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:strTitle message:strMsg delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        alert.tag = 2;
        [alert show];
    }
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
    if (alertView.tag == 2) {
        AppDelegate *appDelegate = kAppDelegate;
        [appDelegate setRootViewController];
    }
}


@end
